package cn.richard.demo.swagger;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import cn.hutool.core.util.RandomUtil;
import cn.richard.demo.swagger.dto.Student;

@Service
public class StudentService {
	private Map<Integer, Student> stuMap = new HashMap<>();
	private List<Student> stuList = new ArrayList<>();
	
	@PostConstruct
	private void init() {
		for(int i=0; i<100; i++) {
			Student stu = new Student().setId(i);
			stu.setName(RandomUtil.randomString("zmvhtqretyuiopdfghjklxcvbnmQWERTYUIASDFGHJKLZXCVBNM", 7))
			   .setGender(i%2==0?"male":"female")
			   .setBirthday(LocalDate.now());
			stuList.add(stu);
			stuMap.put(i, stu);
		}
	}
	
	public List<Student> listAll(){
		return stuList;
	}
	
	public Student getById(Integer id) {
		return stuMap.get(id);
	}
	
	public Student getLast() {
		return stuList.get(stuList.size()-1);
	}
	
	public Student save(Student entity) {
		entity.setId(stuList.size() + 1);
		stuList.add(entity);
		stuMap.put(entity.getId(), entity);
		
		return getLast();
	}
	
	public void remove(Integer id) {
		int id1 = id;
		stuList.remove(id1);
		stuMap.remove(id1);
	}
	
	public Student update(Student entity) {
		remove(entity.getId());
		
		return save(entity);
	}

	public Student getByName(String name) {
		for(Student stu:stuList) {
			if(stu.getName().equals(name)) return stu;
		}
		
		return null;
	}
}
